package com.gwz.cardserver.global;

import com.gwz.cardserver.dto.room.MatchRoom;
import io.netty.channel.ChannelHandlerContext;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.concurrent.ConcurrentHashMap;

@Component
public class MatchCache {
    /**
     * 用户id和房间id
     */
    private ConcurrentHashMap<String, Integer> uidRoomIdMap = new ConcurrentHashMap();
    /**
     * 房间id和房间实体
     */
    private ConcurrentHashMap<Integer, MatchRoom> roomMap = new ConcurrentHashMap();
    /**
     * 代表重用的房间队列
     */
    private LinkedList<MatchRoom> roomList = new LinkedList<>();
    /**
     * 代表 房间id
     */
    private int currentId = -1;

    /**
     * 进入匹配队列 进入匹配房间
     *
     * @param userId
     * @return
     */
    public MatchRoom enter(String userId, ChannelHandlerContext context) {
        // 遍历等待的房间 看下 有没有正在等待的 如果有 把当前玩家加进去
        for (MatchRoom mr : roomMap.values()) {
            // 房间满了
            if(mr.isFull()){
                continue;
            }
            // 没满push进入
            mr.enter(userId,context);
            uidRoomIdMap.put(userId,mr.getId());
            return mr;
        }
        // 没有等待的房间
        MatchRoom room = null;
        if(roomList.size()>0){
            room = roomList.pop();
        }else{
            room = new MatchRoom(++currentId);
        }
        room.enter(userId,context);
        roomMap.put(room.getId(),room);
        uidRoomIdMap.put(userId,room.getId());
        return room;
    }

    /**
     * 离开匹配房间
     * @param uid
     * @return
     */
    public MatchRoom leave(String uid){
        Integer roomId = uidRoomIdMap.get(uid);
        MatchRoom matchRoom = roomMap.get(roomId);
        matchRoom.leave(uid);
        uidRoomIdMap.remove(uid);
        if(matchRoom.isEmpty()){
            roomMap.remove(matchRoom.getId());
            roomList.push(matchRoom);
        }

        return matchRoom;
    }

    /**
     * 判断用户是否正在匹配
     * @param userId
     * @return
     */
    public boolean isMatching(String userId){
        return uidRoomIdMap.containsKey(userId);
    }

    /**
     * 获取玩家所在房间
     * @param userId
     * @return
     */
    public MatchRoom getRoom(String userId){
        Integer roomId = uidRoomIdMap.get(userId);
        MatchRoom matchRoom = roomMap.get(roomId);
        return matchRoom;
    }

    public void destory(MatchRoom room){
        roomMap.remove(room.getId());

        room.getUids().forEach((key,value) ->{
            uidRoomIdMap.remove(key);
        });

        room.setUids(new ConcurrentHashMap<>());
        room.setReadyUids(new ArrayList<>());
        roomList.push(room);

    }


}
